# coding=utf-8
__author__ = 'liubin'

from sqlalchemy import or_, desc
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin, unblock, to_json
from project.models import News

class NewsHandler(HandlerMixin, APIHandler):
    """
    公告API
    """

class ListHandler(NewsHandler):
    """
    公告列表
    """
    __urls__ = [r'/api/news/?']

    @unblock
    def get(self):
        """
        get方法
        :return:
        """
        # 无关字段, 原样返回
        draw = self.get_query_argument('draw', 0)
        # 分页大小
        size = int(self.get_query_argument('size', 0))
        # 第几项开始
        start = int(self.get_query_argument('start', 0))
        # 查询字段
        query = self.get_query_argument('query', '')
        # 排序字段
        order = self.get_query_argument('order', '')
        # 正序或倒叙
        sort = self.get_query_argument('dir', '')
        end = start + size
        newses = self.db_conn.query(News).filter_by(isDeleted=False)
        if query:
            # 条件过滤
            newses = newses.filter(
                or_(
                    News.title.like('%' + query + '%'),
                    News.content.like('%' + query + '%')
                )
            )
        if order:
            # 排序
            if sort == 'desc':
                newses = News.order_by(desc(getattr(News, order)))
            else:
                newses = News.order_by(getattr(News, order))
        # 总件数
        total = newses.count()
        if end:
            # 分页处理
            newses = newses.slice(start, end)
        # 获取list对象
        newses = newses.all()
        # 返回值
        self.success(to_json(newses), draw=draw, total=total)